package com.splant.android.smart.SystemDefinedLevel.AutoUpdateSoft;

/**
 * Created by JimOPC on 15-2-16.
 */
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.TextHttpResponseHandler;
import com.splant.android.smart.GlobalConfig;
import com.splant.android.R;
import com.splant.android.smart.SystemDefinedLevel.AutoStartApp.StartReceiver;
import com.splant.android.smart.SystemDefinedLevel.FilesManager.FilesManager;
import com.splant.android.smart.SystemDefinedLevel.Utils.System_Util;

import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

public class UpdateManager {

    //存放更新APK文件的目录
    private final static String UPDATEFILE_DOWNDIR = "app/android/phone/";
    //存放更新APK文件相应的版本说明路径
    private final  static String UPDATE_CHECKSVRURL = "app/android/phone/update_verson.txt";
    private  static String UPDATE_SAVENAME = "splant_garden.apk";

    private UpdateCallback callback;
    private Context mContext;
    private String updateVersionFileSrc="";//更新的版本文件路径
    //服务器地址
    private String apkFileUrl="";
    //从服务器上下载apk存放文件夹
    private String savefolder = "";
    private AsyncHttpClient client;

    public UpdateManager(Context context, UpdateCallback updateCallback) {

        mContext = context;
        callback = updateCallback;
        getApkFileUrl();
        client=new AsyncHttpClient();

    }

    private static UpdateManager mUpdateManager;
    public static UpdateManager getInstance(Context context,UpdateCallback updateCallback)
    {
        if (mUpdateManager==null){
            synchronized (UpdateManager.class){
                if (mUpdateManager==null)
                    mUpdateManager=new UpdateManager(context,updateCallback);
            }
        }
        return mUpdateManager;
    }

    private void getApkFileUrl()
    {
        apkFileUrl= GlobalConfig.WEB_SERVER_IP_PORT_PATH+UPDATEFILE_DOWNDIR+UPDATE_SAVENAME;
        updateVersionFileSrc= GlobalConfig.WEB_SERVER_IP_PORT_PATH+UPDATE_CHECKSVRURL;
    }

    public void checkVersion()
    {
        downLoadVersionFileHandler.setCharset(System_Util.CHARSETNAME_GBK);
        client.get(updateVersionFileSrc,downLoadVersionFileHandler);
    }

    TextHttpResponseHandler downLoadVersionFileHandler=new TextHttpResponseHandler()
    {
        @Override
        public void onFailure(int i, Header[] headers, String s, Throwable throwable)
        {
            Toast.makeText(mContext,mContext.getString(R.string.system_connectserver_failurestate_txt),Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onSuccess(int i, Header[] headers, String s)
        {
            try
            {
                if (i==HttpStatus.SC_OK)
                {
                    JSONObject versionObj=new JSONObject(s);
                    int newVersionCode=versionObj.getInt("versionCode");
                    String newVersionName=versionObj.getString("versionName");
                    String newVersionInfo=versionObj.getString("versionInfo");
                    int curVersionCode= System_Util.getVersionCode(mContext);

                    boolean hasUpdate=false;
                    if (newVersionCode>curVersionCode)
                    {
                        hasUpdate=true;
                    }
                    callback.checkUpdateCompleted(hasUpdate,newVersionName,newVersionInfo);
                }
                else
                    onFailure(i,headers,s,null);

            } catch (JSONException e) {
                onFailure(i,headers,s,null);
                e.printStackTrace();
            }
        }
    };

    private FileAsyncHttpResponseHandler mFileAsyncHttpResponseHandler;

    public void downloadPackage()
    {

        Object sdObj= FilesManager.getSDcardPath();
        if (sdObj!=null)
        {
            savefolder=sdObj.toString();
        }
        else
        {
           // Toast.makeText(mContext,"无法获取到SD卡",Toast.LENGTH_LONG).show();
            return;
        }

        String saveFileSrc=savefolder+"/"+UPDATE_SAVENAME;
        File downLoadFile=new File(saveFileSrc);
        try
        {
            downLoadFile.createNewFile();
        }
        catch (IOException e)
        {
            callback.downloadCompleted(false,"createNewFileFailure");
        }

        mFileAsyncHttpResponseHandler=new FileAsyncHttpResponseHandler(downLoadFile)
        {
            @Override
            public void onFailure(int i, Header[] headers, Throwable throwable, File file) {
                callback.downloadCompleted(false,"downLoadFailure");
            }

            @Override
            public void onSuccess(int i, Header[] headers, File file) {
                if (i==HttpStatus.SC_OK)
                {
                    callback.downloadCompleted(true,"downLoadSuccess");
                }
                else
                    onFailure(i,headers,null,file);

            }
            @Override
            public void onProgress(long bytesWritten, long totalSize) {
                super.onProgress(bytesWritten, totalSize);

                double d=(double)bytesWritten;
                double pv=d/totalSize;

                int p= (int) (pv*100);
                callback.downloadProgressChanged(p);
            }
            @Override
            public void onRetry(int retryNo) {
                super.onRetry(retryNo);
                // 返回重试次数
            }
        };

        client.get(apkFileUrl, mFileAsyncHttpResponseHandler);
    }

    public void setApkFileUrl(String apkUrl)
    {
        apkFileUrl=apkUrl;
        UPDATE_SAVENAME=apkFileUrl.substring(apkFileUrl.lastIndexOf("/")+1);
    }

    public void cancelDownLoad()
    {
        callback.downloadCanceled();
    }

    public void popInstall()
    {
        File f= new File(savefolder, UPDATE_SAVENAME);
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setAction("android.intent.action.VIEW");
        i.addCategory("android.intent.category.DEFAULT");
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        String type = getMIMEType(f);

        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){

            Uri uri= FileProvider.getUriForFile(mContext,"com.splant.android.fileprovider",f);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            i.setDataAndType(uri,type);

        }else{
            i.setDataAndType(Uri.fromFile(f), type);
        }

        mContext.startActivity(i);
    }

    public String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }

    public interface UpdateCallback
    {
        void checkUpdateCompleted(Boolean hasUpdate,String updateTitle,String updateMessage);
        void downloadProgressChanged(int progress);
        void downloadCanceled();
        void downloadCompleted(Boolean sucess, CharSequence errorMsg);
    }

    //*************************静默安装
    private String cmd_install = "pm install -r ";
    private String cmd_uninstall = "pm uninstall ";
    public void silentInstall()
    {
        String cmd=cmd_install+savefolder+"/"+UPDATE_SAVENAME;
        excuteSuCMD(cmd);
    }

    protected int excuteSuCMD(String cmd) {
        try
        {
            Process process = Runtime.getRuntime().exec("su");
            DataOutputStream dos = new DataOutputStream(
                    (OutputStream) process.getOutputStream());
            // 部分手机Root之后Library path 丢失，导入path可解决该问题
            dos.writeBytes((String) "export LD_LIBRARY_PATH=/vendor/lib:/system/lib\n");
            cmd = String.valueOf(cmd);
            dos.writeBytes((String) (cmd + "\n"));
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            process.waitFor();
            int result = process.exitValue();
            return (Integer) result;
        }
        catch (Exception localException)
        {
            localException.printStackTrace();
            return -1;
        }
    }

    //设置自动启动应用
    public void setAutoStart(Context context)
    {
        Intent ite = new Intent(context, StartReceiver.class);
        ite.setAction("install_and_start");
        PendingIntent SENDER = PendingIntent.getBroadcast(context, 0, ite,
                PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager ALARM = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
        ALARM.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 30000, SENDER);
    }

    //*************************静默安装
}
